package com.lancoo.hanvon;

import android.Manifest;
import android.app.Activity;
import android.content.Context;

import com.hanvon.HWCloudManager;
import com.lancoo.ai.test.base.lib.Global;
import com.lancoo.ai.test.base.lib.JsonUtil;
import com.lancoo.ai.test.base.lib.permission.PermissionsManager;
import com.lancoo.ai.test.base.lib.permission.PermissionsResultAction;
import com.lancoo.hanvon.sdk.SDK_GeneralTextLanguage;

import java.util.ArrayList;

public class GeneralText {
    // private static final String KEY = "51a7cadb-c139-4b03-a770-c2ab02fe1dbc";
//    private static final String KEY = "725ba657-0a99-4dbe-8291-d9b300eb7627";// 植志洪提供
    private static final String KEY = "3e1e4e36-5763-4353-9562-539ddf2bf14d";// 朱凯提供

    private String mKey;
    private HWCloudManager mHWCloudManager;
    private OnGeneralTextCallback mCallback;

    @Deprecated
    public GeneralText() {
        this(KEY);
    }

    public GeneralText(String key) {
        mKey = key;
    }

    public void setCallback(Activity activity, OnGeneralTextStateChangeCallback callback) {
        if (callback == null) return;
        mCallback = callback;
        requestAllPermissions(activity);
    }

    private void requestAllPermissions(Activity activity) {
        String[] permissions = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_PHONE_STATE,
        };
        final Context context = activity.getApplicationContext();
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(activity, permissions, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                mHWCloudManager = new HWCloudManager(context, mKey) {
                    @Override
                    public String generateID() {
                        return Tool.generateIDCompat(context);
                    }

                    @Override
                    public String generalTextLanguage(String isText, String picPath) {// 优化超时时长，原SDK10秒钟太短了
                        String androidKey = Tool.findFieldValueOfHWCloudManager(this, "androidKey");
                        String whitelist = Tool.findFieldValueOfHWCloudManager(this, "whitelist");
                        return SDK_GeneralTextLanguage.GeneralTextDiscern(isText, picPath, androidKey, whitelist);
                    }
                };
                ((OnGeneralTextStateChangeCallback) mCallback).onManagerCreated(false);
            }

            @Override
            public void onDenied(String permission) {
                ((OnGeneralTextStateChangeCallback) mCallback).onManagerCreated(true);
            }
        });
    }

    public void onRequestPermissionsResult(String[] permissions, int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

    public void setCallbackEasy(Context context, OnGeneralTextCallback callback) {
        if (callback == null) return;
        mCallback = callback;
        mHWCloudManager = new HWCloudManager(context, mKey) {
            @Override
            public String generateID() {
                return "GT2021";
            }

            @Override
            public String generalTextLanguage(String isText, String picPath) {// 优化超时时长，原SDK10秒钟太短了
                String androidKey = Tool.findFieldValueOfHWCloudManager(this, "androidKey");
                String whitelist = Tool.findFieldValueOfHWCloudManager(this, "whitelist");
                return SDK_GeneralTextLanguage.GeneralTextDiscern(isText, picPath, androidKey, whitelist);
            }
        };
    }

    public void recognize(final String picturePath) {
        if (mHWCloudManager == null) return;
        Global.submit(new Runnable() {
            @Override
            public void run() {
                // 0：返回文本，1：返回坐标、字符数、文本等
                final String data = mHWCloudManager.generalTextLanguage("0", picturePath);
                Result result = JsonUtil.parseJson(data, Result.class);
                final String text;
                final boolean isOkRequest, isKeyUseful;
                if (result != null) {
                    text = result.get();
                    isOkRequest = true;
                    isKeyUseful = !"434".equals(result.code);
                } else {
                    text = "";
                    isOkRequest = false;
                    isKeyUseful = true;
                }
                Global.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mCallback.onGeneralText(isOkRequest, isKeyUseful, text);
                    }
                });
            }
        });
    }

    public static class Result {
        String code;// 返回码，0成功
        String result;// 消息内容
        ArrayList<Document> documents;// 文本内容

        public String appendContend="";

        public String get() {
            if (!"0".equals(code) || documents == null || documents.isEmpty()) return "";
            StringBuilder sb = new StringBuilder();
            int size = documents.size();
            for (int i = 0; i < size; i++) {
                Document document = documents.get(i);
                String text = document.text;
                if (text == null) text = "";
                sb.append(text);
                if (i != size - 1) sb.append(" ");
            }
            return sb.toString().trim();
        }
    }

    private static class Document {
        String text;
    }

    /**
     * 430：key illegal 没有有效的key
     * 431：whitelist illegal 请求不在白名单范围内
     * 432：fingerprint illegal
     * 433：package name illegal
     * 434：serviceCode illegal 您没有申请相应的服务，或服务的次数已到临界值，或服务已到期
     * 437：input is null 您的请求参数为空
     * 438：input json format invalid 您的请求参数json格式非法
     * 439：image is null 您的请求参数中图片数据为空
     * 3130：Text recognize core service exception 识别服务错误
     * 3120：Text recognize core exception不是有效的图片，请确保：图像尺寸在960*640和2048*1024之间; 图像大小:200K左右（50k-1536k）JPEG压缩比65%-85%;
     */
}
